﻿using System.ComponentModel;

namespace WebApi.Commons.Helpers
{
    /// <summary>
    /// 枚举帮助类
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 根据姓名获取枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        public static T GetEnumByName<T>(string name) where T : Enum
        {
            return (T)Enum.Parse(typeof(T), name, true);
        }

        /// <summary>
        /// 根据值获取枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T GetEnumByValue<T>(int value) where T : Enum
        {
            return (T)Enum.ToObject(typeof(T), value);
        }

        /// <summary>
        /// 根据字符串获取描述
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDescriptionByName<T>(string name) where T : Enum
        {
            try
            {
                return GetEnumByName<T>(name).GetDescription();
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 根据枚举值获取描述
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDescriptionByValue<T>(int value) where T : Enum
        {
            try
            {
                return GetEnumByValue<T>(value).GetDescription();
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取描述
        /// </summary>
        /// <returns></returns>
        public static string GetDescription(this Enum enumeration)
        {
            var type = enumeration.GetType();
            var memInfo = type.GetMember(enumeration.ToString());
            if (null != memInfo && memInfo.Length > 0)
            {
                var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (null != attrs && attrs.Length > 0)
                {
                    var attr = (DescriptionAttribute)attrs[0];
                    return attr.Description;
                }
            }
            return string.Empty;            
        }
    }
}
